<template>
  <div class="container" @mousedown="onMouseDown">
    <!-- use v-for to render multiple DraggableResizableRectangle components -->
    <DragRectangle
      v-for="(rectangle, index) in rectangles"
      :key="index"
      :ref="`rectangleRef_${index}`"
      :initialX="rectangle.x"
      :initialY="rectangle.y"
      :initialWidth="rectangle.width"
      :initialHeight="rectangle.height"
      :isSelected="selectedRectangleIndex === index"
      @dragging="onRectangleDragging(index, $event)"
      @resizing="onRectangleResizing(index, $event)"
      @mousedown="onRectangleMouseDown(index)"
    />
  </div>
</template>

<script>
import DragRectangle from "./DragRectangle.vue";

export default {
  components: {
    DragRectangle,
  },
  data() {
    return {
      rectangles: [], // 存储多个矩形组件的数组
      isDragging: false,
      draggingX: 0,
      draggingY: 0,
      selectedRectangleIndex: -1, // 用于标记选中的矩形索引
    };
  },
  methods: {
    onMouseDown(event) {
      const hitRectangle = this.rectangles.some((rectangle, index) => {
        console.log("rectangle", index);
        console.log(this.$refs[`rectangleRef_${index}`]);
        console.log(this.$refs[`rectangleRef_${index}`][0]);
        const rect =
          this.$refs[`rectangleRef_${index}`][0].$el.getBoundingClientRect();

        console.log(event);
        console.log(event.clientX);
        console.log(rect.left);
        console.log(rect.right);

        console.log(event.clientY);
        console.log(rect.top);
        console.log(rect.bottom);

        return (
          event.clientX >= rect.left &&
          event.clientX <= rect.right &&
          event.clientY >= rect.top &&
          event.clientY <= rect.bottom
        );
      });

      console.log("hitRectangle");
      console.log(hitRectangle);

      if (!hitRectangle) {
        this.rectangles.push({
          x: event.clientX,
          y: event.clientY,
          width: 200,
          height: 100,
        });
      }
    },
    onRectangleMouseDown(index) {
      console.log("onRectangleMouseDown", index);
      this.selectedRectangleIndex = index;
    },
    onRectangleDragging(index, { x, y }) {
      this.rectangles[index].x = x;
      this.rectangles[index].y = y;
    },
    onRectangleResizing(index, { width, height }) {
      this.rectangles[index].width = width;
      this.rectangles[index].height = height;
    },
  },
};
</script>

<style scoped>
/* 省略样式代码，根据需要添加 */
.container {
  position: relative;
  width: 100%;
  height: 100vh;
  border: 1px solid salmon;
}
</style>
